//注意我这边用的是esp12e模块，淘宝16块左右，所以有16引脚，esp8266也可以烧制以下程序

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiUdp.h>
#include <WakeOnLan.h>
#include <ArduinoJson.h>
WiFiUDP UDP;
WakeOnLan WOL(UDP);
// Update these with values suitable for your network.

const char* ssid = "Xiaomi_5C2D";
const char* password = "82370288";
const char* mqttServer = "192.168.31.129";
const int mqttPort = 1883;
const char* mqttUserName = "huyong";
const char* mqttPassword = "San12guo";
const char* cmdTopic = "cmdTopic";
const char* willTopic = "willTopic";
const char* onlineTopic = "onlineTopic"; 
const char* clientId = "clientId001";

WiFiClient espClient;
PubSubClient client(espClient);

int lightPin = 2;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }  
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  String command = "";
  for (int i = 0; i < length; i++) {
    command += (char)payload[i];
  }
//
  handlePayload(String(topic), command); 
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    //详细参数说明请查看文档
    if (client.connect(clientId,mqttUserName,mqttPassword,willTopic,1,0,clientId)) {
      Serial.println("connected");
      client.publish(onlineTopic, clientId);
      client.subscribe(cmdTopic, 1);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void wakeMyPC(String macAddr) {
//    const char *MACAddress = "01:23:45:67:89:AB";
  
    WOL.sendMagicPacket(macAddr); // Send Wake On Lan packet with the above MAC address. Default to port 9.
    // WOL.sendMagicPacket(MACAddress, 7); // Change the port number
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);

  WOL.setRepeat(3, 100); // Optional, repeat the packet three times with 100ms between. WARNING delay() is used between send packet function.
  WOL.calculateBroadcastAddress(WiFi.localIP(), WiFi.subnetMask()); // Optional  => To calculate the broadcast address, otherwise 255.255.255.255 is used (which is denied in some networks).
  
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

//处理命令
void handlePayload(String topic, String payload) {
//String handlePayload(byte* payload) {
  Serial.println("Topic: "+ topic);
  DynamicJsonDocument doc(1024);
  deserializeJson(doc, payload);
  JsonObject obj = doc.as<JsonObject>();
  
  String cmd = obj["cmd"];
  Serial.println("Cmd:" + cmd);
  
  
  
  if (String(cmdTopic).equals(topic)) {
    //light command
    if (String("lightOn").equals(cmd)) {
      client.publish(onlineTopic, cmd.c_str());
      digitalWrite(lightPin, HIGH);
    } else if (String("lightOff").equals(cmd)) {
      client.publish(onlineTopic, cmd.c_str());
      digitalWrite(lightPin, LOW);
    } 
    else if (String("wakeMyPC").equals(cmd)) {
      String addr = obj["addr"];
      Serial.println("wakeMyPC:"+addr);
      String msg = "Cmd:"+cmd+",addr:"+addr;
      client.publish(onlineTopic, msg.c_str());
      wakeMyPC(addr);
    } 
  }
}
